﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        Int32 i = 0;
        String urlAnterior = null;
        private const String CREDENCIAL = "amV1ZGkuYXJhdWpvLGRvaXNNSUxlMTQ=";

        private String UsuarioProxy
        {
            get
            {
                String valor = Encoding.UTF8.GetString(Convert.FromBase64String(CREDENCIAL));
                return valor.Split(',')[0];
            }
        }

        private String SenhaProxy
        {
            get
            {
                String valor = Encoding.UTF8.GetString(Convert.FromBase64String(CREDENCIAL));
                return valor.Split(',')[1];
            }
        }

        public Form1()
        {
            InitializeComponent();

            webBrowser1.Navigate("http://br.bing.com/");
            Task.Factory.StartNew
                (() =>
                {
                    for (int i = 0; i < 12; i++)
                    {
                        this.FInfo = "Iniciando ... " + i.ToString("00") + "/12";
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(500);
                    }
                    this.FInfo = "Carregando...";
                    webBrowser1.BeginInvoke(new Action(BaixarImagens));
                });
        }

        private void BaixarImagens()
        {
            try
            {
                if (this.IsDisposed) { return; }
                Application.DoEvents();
                HtmlElement botaoImgAnterior = webBrowser1.Document.GetElementById("sh_igl");
                String pastaUsuario = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                String pastaImg = Path.Combine(pastaUsuario, "temp");
                if (Directory.CreateDirectory(pastaImg).Exists)
                {
                    pastaImg = Path.Combine(pastaImg, "BING");
                    if (Directory.CreateDirectory(pastaImg).Exists)
                    {
                        for (i = 1; i < 9; i++)
                        {
                            this.FInfo = "Acessando imagem 0" + i.ToString();
                            String urlImg = GetUrlImg();

                            if (urlImg != null && urlImg.Length > 18 && urlAnterior != urlImg)
                            {
                                WebClient webc = new WebClient();
                                webc.Proxy = WebRequest.DefaultWebProxy;
                                if (webc.Proxy != null && webc.Proxy.Credentials == null)
                                { webc.Proxy.Credentials = new NetworkCredential(this.UsuarioProxy, this.SenhaProxy); }
                                this.FInfo = "Baixando IMG 0" + i.ToString() + Environment.NewLine + urlImg;
                                Application.DoEvents();
                                System.Threading.Thread.Sleep(1000);
                                Application.DoEvents();
                                String nomeArquivo = String.Format(Path.Combine(pastaImg, "BING" + i.ToString() + ".jpg"));
                                urlImg = urlImg.Replace("http://br.bing.comhttp://www.bing.com", "http://www.bing.com");
                                webc.DownloadFile(urlImg, nomeArquivo);

                                String hashFile = CalcularHashArquivo(nomeArquivo);
                                String novoArquivo = Path.Combine(pastaImg, hashFile + ".jpg");
                                if (!File.Exists(novoArquivo))
                                    File.Move(nomeArquivo, novoArquivo);
                                else File.Delete(nomeArquivo);
                            }
                            urlAnterior = urlImg;
                            while (i < 8 && urlAnterior == GetUrlImg())
                            {
                                this.FInfo = String.Empty;
                                webBrowser1.Focus();
                                Application.DoEvents();
                                botaoImgAnterior.Focus();
                                Application.DoEvents();
                                botaoImgAnterior.InvokeMember("click");
                                Application.DoEvents();
                            }
                        }
                        webBrowser1.Navigate("http://br.bing.com/");
                        this.FInfo = "Concluido.";
                    }
                }
            }
            catch (Exception ex)
            {
                this.Hide();
                MessageBox.Show(ex.Message, "Erro ao Baixar Img", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally { Application.Exit(); }
        }

        private String CalcularHashArquivo(String nomeArquivo)
        {
            String hashSHA1Text = null;
            if (File.Exists(nomeArquivo))
            {
                using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
                {
                    using (FileStream sr = new FileStream(nomeArquivo, FileMode.Open))
                    {
                        using (BufferedStream bs = new BufferedStream(sr))
                        {
                            Byte[] hashSHA1 = sha1.ComputeHash(bs);
                            hashSHA1Text = BitConverter.ToString(hashSHA1).Replace("-", "");
                            bs.Close();
                        }
                        sr.Close();
                    }
                    sha1.Clear();
                }
                return hashSHA1Text;
            }
            else return null;
        }

        private String GetUrlImg()
        {
            String titulo = this.label1.Text;
            if (this.IsDisposed) { return null; }

            this.FInfo = "Aguardando proxima imagem ser carregada...";
            Application.DoEvents();
            System.Threading.Thread.Sleep(1000);
            Application.DoEvents();

            HtmlElement img = webBrowser1.Document.GetElementById("bgDiv");
            String urlImg = img.Style;

            if (!String.IsNullOrEmpty(urlImg))
            {
                String[] styles = urlImg.Split(';');
                foreach (String item in styles)
                {
                    if (item.Trim().ToUpper().StartsWith("BACKGROUND-IMAGE:"))
                    {
                        urlImg = item.Trim();
                        urlImg = urlImg.Replace("BACKGROUND-IMAGE:", String.Empty);
                        urlImg = urlImg.Replace("background-image:", String.Empty);
                        urlImg = urlImg.Trim();
                        urlImg = urlImg.Replace("\"", String.Empty);
                        urlImg = urlImg.Trim();
                        urlImg = urlImg.Replace("URL(", String.Empty);
                        urlImg = urlImg.Replace("url(", String.Empty);
                        urlImg = urlImg.Trim();
                        urlImg = urlImg.Replace(")", String.Empty);
                        urlImg = urlImg.Trim();
                        break;
                    }
                }
                /// urlImg = urlImg.ToUpper();
                if (!String.IsNullOrWhiteSpace(urlImg))
                {
                    this.FInfo = titulo + Environment.NewLine + urlImg + Environment.NewLine + "getURL";
                    if (!urlImg.ToUpper().StartsWith("HTTP://"))
                    { urlImg = "http://br.bing.com" + urlImg; }
                    this.FInfo = titulo + Environment.NewLine + urlImg + Environment.NewLine + "getURL";
                }
            }

            return urlImg;
        }

        public string FInfo
        {
            set
            {
                label1.Invoke(new Action(() =>
                {
                    label1.Text = value;
                    label1.Update();
                }));
            }
        }
    }
}
